package com.zhitong.ztblog.services.servicesImp;

import com.zhitong.ztblog.utils.DateUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class FileService {

    public Map<String, String> uploadImage(MultipartFile multipartFile, HttpServletRequest request) {
//        改变文件名,防止重复
        String fileName="";
        String originalFilename = multipartFile.getOriginalFilename();
        fileName=new Date().getTime()+originalFilename;

//        设置文件的保存路径
//        ServletContext context=request.getServletContext();
//        String realPath = request.getSession().getServletContext().getRealPath("/static/images");
//        System.out.println(realPath);
        String path = null;
        String realPath=null;
        try {
             path = ResourceUtils.getURL("classpath:").getPath()+"static/images";
             realPath = path.replace('/', '\\').substring(1,path.length());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        String dataPath = DateUtil.format(new Date(),"yyyy-MM-dd");
        File file=new File(realPath+"/"+dataPath);
        if (!file.exists()){
            file.mkdirs();
        }
        try {
            multipartFile.transferTo(new File(file,fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        Map<String,String> map=new HashMap<>();
        map.put("realPath",realPath+"\\"+dataPath+"\\"+fileName);
        map.put("imageUrl","images"+'/'+dataPath+"/"+fileName);
        return map;
    }

    public boolean deleteImage(String realPath){
        File file=new File(realPath);
        if (file.exists()){
            return file.delete();
        }else {
            return true;
        }
    }

}
